<template>
  <div class="card" style="margin-bottom: 5px">
    <el-input clearable @clear="load" style="width: 260px; margin-right: 5px;" v-model="data.title" placeholder="请输入标题查询" :prefix-icon="Search"></el-input>
    <el-button type="primary" @click="load">查 询</el-button>
    <el-button type="info" @click="reset">重 置</el-button>
  </div>
  <div class="card"  style="margin-bottom: 5px" v-if="data.user.role === 'USER'">
    <el-button type="primary" @click="headleAdd">新   增</el-button>
  </div>
  <div class="card" style="margin-bottom: 5px">
    <el-table :data="data.tableData" style="width: 100%" :header-cell-style="{ color:'#333',backgroundColor:'#dde8ff'}">
      <el-table-column label="头像" width="100">
        <template #default="scope">
          <el-image :preview-src-list="[scope.row.img]" :preview-teleported="true" v-if="scope.row.img" :src="scope.row.img" alt="" style="width: 50px; height: 50px; display: block; border-radius: 5px"/>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="攻略标题" />
      <el-table-column prop="categoryTitle" label="攻略分类" />
      <el-table-column prop="userName" label="发布用户" />
      <el-table-column prop="content" label="攻略内容" >
        <template v-slot="scope">
          <el-button type="primary" @click="viewContent(scope.row.content)" >点击查看</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="time" label="发布时间" />
      <el-table-column v-if="data.user.role === 'ADMIN'" label="操作" width="100">
        <template #default="scope">
          <el-button type="primary" icon="Edit" circle @click="headleEdit(scope.row)" ></el-button>
          <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)" ></el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="care">
    <el-pagination
        v-model:current-page="data.pageNum"
        v-model:page-size="data.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 15]"
        :total="data.total"
        @current-change="load"
        @size-change="load"
    />
  </div>
  <el-dialog v-model="data.formVisible" title="旅游攻略信息" destroy-on-close width="60%">
    <el-form ref="formRef" :model="data.form" label-width="80px" style="padding: 20px 30px 10px 0">
      <el-form-item prop="avatar" label="头像" >
        <el-upload
            action="http://localhost:9999/files/upload"
            :headers="{token: data.user.token}"
            :on-success="handleFileSuccess"
            list-type="picture"
        >
          <el-button type="primary">上传头像</el-button>
        </el-upload>
      </el-form-item>
            <el-form-item prop="categoryId" label="攻略分类" >
              <el-select v-model="data.form.categoryId" placeholder="请选择攻略分类" style="width: 100%;">
                <el-option
                  v-for="time in data.category"
                  :key="time.id"
                  :label="time.title"
                  :value="time.id"
                  />
              </el-select>
            </el-form-item>
      <el-form-item prop="title" label="攻略标题" >
        <el-input v-model="data.form.title" autocomplete="off" placeholder="请输入攻略标题"/>
      </el-form-item>
      <el-form-item prop="content" label="攻略详情" >
        <div style="border: 1px solid #ccc">
          <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :mode="mode"
          />
          <Editor
              style="height: 500px; overflow-y: hidden;"
              v-model="data.form.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.formVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="data.contentVisible" title="攻略内容" width="70%">
    <div v-html="data.currentContent" style="max-height: 500px; overflow-y: auto;"></div>
  </el-dialog>
</template>

<script setup>
import request from "@/utils/request.js";
import {Search} from "@element-plus/icons-vue";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, reactive } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
const formRef = ref()
const emit = defineEmits(["updateUser"])
const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || '{}'),
  username: '',
  pageNum: 1,
  pageSize: 5,
  total: 6,
  tableData:  [],
  title: '',
  formVisible: false,
  form: {},
  contentVisible: false,
  currentContent: '',
  category:[],
})

/* wangeditor5 初始化开始*/
const editorRef = shallowRef()   // 编辑器实例，必须用 shallowRef
const mode = 'default'
const editorConfig = { MENU_CONF: {} }
// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
  headers: { token: data.user.token },
  server: 'http://localhost:9999/files/wang/upload',  //服务器图片上传接口地址
  fieldName: 'file' //服务器图片上传接口参数
}

// 组件销毁时，及时销毁编辑器 否则可能会造成内存泄漏
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor === null) {
    return editor.destroy()
  }
})

// 记录编辑器实例
const handleCreated = (editor) => {
  editorRef.value = editor
}
/* 编辑器 初始化结束*/

// 数据获取查询按钮
const load = () =>{
  request.get('category/selectAll').then(res =>{
    if(res.code === '200'){
      data.category =res.data
      console.log(data.category)
    }else {
      ElMessage.error(res.msg)
    }
  })
  request.get('introduction/selectPage',{
    params:{
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      title:data.title
    }
  }).then(res =>{
    if(res.code === '200'){
      data.tableData =res.data.list
      data.total = res.data.total
      emit("updateUser")
    }else {
      ElMessage.error(res.msg)
    }
  })
}
load()

const viewContent = (content) =>{
  data.currentContent = content
  data.contentVisible = true
}
// 重置按钮
const reset = () =>{
  data.title = ''
  load()
}

// 新增按钮
const headleAdd = () =>{
  data.form = {}
  data.formVisible = true
}

//  保存按钮 判断是新增还是修改
const save = () =>{
  console.log(data.form)
  if(data.form.id){
    update()
  }else {
    add()
  }
}

// 新增保存按钮
const add = () =>{
  formRef.value.validate(valid => { // formref 是表单的引用 表单验证
    if(!valid){
      return false
    }
    request.post('introduction/add',data.form).then(res =>{
      if(res.code === '200'){
        data.formVisible = false
        ElMessage.success('新增成功')
        load()
      }else {
        ElMessage.error(res.msg)
      }
    })
  })
}

// 修改保存按钮
const headleEdit = (row) =>{
  data.form = JSON.parse(JSON.stringify(row)) // 深拷贝
  data.formVisible = true
}

// 删除按钮
const del = (id) =>{
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '删除确认', {type: 'warning',}).then(res => {
    console.log(id)
    request.delete('/introduction/delete/'+id).then(res =>{
      if(res.code === '200'){
        ElMessage.success('删除成功')
        load()
      }
    }).catch(() => {
      ElMessage.error(res.msg)
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  });
}

// 修改编辑按钮
const update = () =>{
  formRef.value.validate(valid => { // formref 是表单的引用 表单验证
    if(!valid){
      return false
    }
    request.put('introduction/update',data.form).then(res =>{
      if(res.code === '200'){
        data.formVisible = false
        ElMessage.success('修改成功')
        load()
      }else {
        ElMessage.error(res.msg)
      }
    })
  })
}

const handleFileSuccess = (res) => {
  data.form.img = res.data
}
</script>
<style scoped>

</style>